<?php

namespace app\result;

use app\model\user\Cashflows;
use app\model\user\UserBudget;

class BudgetResult extends BaseResult
{
    //更新预算金额
    public function update_amount($args)
    {
        $user_id = intval($args['user_id'] ?? 0);
        $budget_id = intval($args['budget_id'] ?? 0);
        if (!$budget_id) {
            return self::error_return('请选择预算');
        }
        if (!$user_id) {
            return self::error_return('参数有误');
        }
        $budget = (new UserBudget())->data_get(['budget_id' => $budget_id, 'user_id' => $user_id, 'del_time' => 0]);
        //更新预算
        if ($budget['type'] == 10) {
            $amount = (new Cashflows())->data_sum(['user_id' => $user_id, 'budget_id' => $budget['budget_id'], 'type' => 10], 'amount');
            $up = [
                'in_amount' => $amount
            ];
        } elseif ($budget['type'] == 20) {
            $amount = (new Cashflows())->data_sum(['user_id' => $user_id, 'budget_id' => $budget['budget_id'], 'type' => 20], 'amount');
            $up = [
                'out_amount' => $amount
            ];
        } else {
            $out_amount = (new Cashflows())->data_sum(['user_id' => $user_id, 'budget_id' => $budget['budget_id'], 'type' => 20], 'amount');
            $in_amount = (new Cashflows())->data_sum(['user_id' => $user_id, 'budget_id' => $budget['budget_id'], 'type' => 10], 'amount');
            $up = [
                'out_amount' => $out_amount,
                'in_amount' => $in_amount
            ];
        }
        $res = (new UserBudget())->data_update(['budget_id' => $budget['budget_id']], $up);
        return $res;
    }

    public function list($user_id, $args)
    {
        $page = intval($args['page'] ?? 1);
        $limit = intval($args['limit'] ?? 10);
        $keywords = trim($args['keywords'] ?? '');
        $data_type = trim($args['data_type'] ?? '');
        if ($data_type == 'option') {
            return $this->list_option($user_id, $args);
        }
        $field = 'budget_id,type,title,amount,out_amount,in_amount,time_limit,start_time,end_time,remark';
        $where[] = ['user_id', '=', $user_id];
        $where[] = ['del_time', '=', 0];
        if ($keywords) {
            $where[] = ['title', 'like', '%' . $keywords . '%'];
        }
        $model = new UserBudget();

        $total = $model->data_count($where);

        $data = $model->data_list($where, $field, 'sort desc budget_id desc', $page, $limit);
        if ($data) {
            foreach ($data as &$v) {
                $v['time_set'] = '不限';
                if ($v['time_limit']) {
                    $v['time_set'] = date('Y/m/d', $v['start_time']) . '~' . date('Y/m/d', $v['end_time']);
                }
                if ($v['type'] == 10) {
                    $v['leave_amount'] = bcsub($v['amount'], $v['in_amount'], 2);
                    if ($v['in_amount'] > $v['amount']) {
                        $v['ext_amount'] = bcsub($v['in_amount'], $v['amount'], 2);
                    }
                } elseif ($v['type'] == 20) {
                    $v['leave_amount'] = bcsub($v['amount'], $v['out_amount'], 2);
                    if ($v['out_amount'] > $v['amount']) {
                        $v['ext_amount'] = bcsub($v['out_amount'], $v['amount'], 2);
                    }
                } else {
                    //综合
                    $v['leave_amount'] = bcsub($v['amount'], $v['out_amount'], 2);
                    //收支差额,利润
                    $v['profit'] = bcsub($v['in_amount'], $v['out_amount'], 2);
                }
                if ($v['leave_amount'] <= 0) {
                    $v['leave_amount'] = '0.00';
                    $v['percent'] = '0%';
                } else {
                    $v['percent'] = bcmul(bcdiv($v['leave_amount'], $v['amount'], 4), 100, 2) . '%';
                }
            }
            unset($v);
        }

        return $this->success_return('success', ['total' => $total, 'list' => $data]);
    }

    public function list_option($user_id, $args, $from_ready = false)
    {
        $keywords = trim($args['keywords'] ?? '');
        $is_all = intval($args['is_all'] ?? 0) && !$from_ready;
        $type = intval($args['type'] ?? 0);
        $limit = '100';
        $page = '1';
        $field = 'budget_id as `value`,title,amount,type';
        $where[] = ['user_id', '=', $user_id];
        $where[] = ['del_time', '=', 0];
        if ($keywords) {
            $where[] = ['title', 'like', '%' . $keywords . '%'];
        }
        if ($type === 10) {
            $where[] = ['type', 'in', '10,0'];
        } elseif ($type === 20) {
            $where[] = ['type', 'in', '20,0'];
        }
        $model = new UserBudget();
        $whereOrStr = "time_limit=:time_limit or (start_time<=:start_time and end_time>=:end_time)";
        $whereOrBind = ['time_limit' => 0, 'start_time' => time(), 'end_time' => strtotime(date('Y-m-d 23:59:59'), time())];
        if ($is_all) {
            $whereOrStr = 'time_limit in (0,1) ';
            $whereOrBind = [];
        }
        $data = $model
            ->field($field)
            ->where($where)
            ->whereRaw($whereOrStr, $whereOrBind)
            ->order('sort desc,budget_id desc')
            ->select();
        if ($data) {
            foreach ($data as &$v) {
                $v['label'] = $v['title'] . '(' . $v['amount'] . '元)';
            }
            unset($v);
        }
        if ($from_ready) {
            return $data;
        }

        return $this->success_return('success', ['list' => $data]);
    }

    public function get($user_id, $args)
    {
        $budget_id = intval($args['budget_id'] ?? 0);
        if (!$budget_id) {
            return self::error_return('请选择预算');
        }
        $model = new UserBudget();
        $data = $model->data_get(['budget_id' => $budget_id, 'user_id' => $user_id, 'del_time' => 0]);
        if (!$data) {
            return self::error_return('预算不存在');
        }
        $data['start_time'] = $data['time_limit'] ? date('Y-m-d', $data['start_time']) : '';
        $data['end_time'] = $data['time_limit'] ? date('Y-m-d', $data['end_time']) : '';
        $data['time_limit'] = boolval($data['time_limit']);
        return $this->success_return('success', [
            'info' => $data
        ]);
    }

    public function action($user_id, $args)
    {
        $rules = [
            ['title', 'empty|max:120|min:1', '反馈内容不能为空|反馈内容长度不能大于120字符|反馈内容长度不能小于1个字'],
            ['amount', 'empty|min:0.01|max:999999999', '金额不能为空|金额不能小于0|金额不能大于999999999'],
        ];
        if (!empty($args['time_limit'])) {
            $rules[] = ['time_limit', 'empty', '时间限制不能为空'];
            $rules[] = ['start_time', 'empty', '开始时间不能为空'];
        }
        $check = check_param($args, $rules);
        if ($check['status'] != 0) {
            return self::error_return($check['msg']);
        }
        if (!empty($args['remark']) && mb_strlen($args['remark']) > 200) {
            return self::error_return('备注不能超过200个字');
        }
        if ($args['amount'] < 0 || $args['amount'] > 999999999) {
            return self::error_return('预算金额不能小于0或大于999999999');
        }
        $model = new UserBudget();
        $budget_id = intval($args['budget_id'] ?? 0);
        if ($budget_id) {
            $data = $model->data_get(['budget_id' => $budget_id, 'user_id' => $user_id, 'del_time' => 0]);
            if (!$data) {
                return self::error_return('预算不存在');
            }
        }
        $baseData = [
            'sort' => intval($args['sort'] ?? 0),
            'user_id' => $user_id,
            'title' => $args['title'],
            'type' => $args['type'] ?? 0,
            'amount' => $args['amount'],
            'remark' => $args['remark'] ?? '',
            'time_limit' => $args['time_limit'] ?? 0,
            'start_time' => $args['time_limit'] ? strtotime($args['start_time']) : 0,
            'end_time' => $args['time_limit'] ? strtotime($args['end_time']) : 0,
        ];
        if ($baseData['end_time'] < $baseData['start_time']) {
            return self::error_return('结束时间不能小于开始时间');
        }
        if ($budget_id) {
            $model->data_update(['budget_id' => $budget_id], $baseData);
            return self::success_return('修改成功');
        }
        $model->data_add($baseData);
        return self::success_return('添加成功');
    }

    public function delete($user_id, $args)
    {
        $budget_id = intval($args['budget_id'] ?? 0);
        if (!$budget_id) {
            return self::error_return('请选择预算');
        }
        $model = new UserBudget();
        $data = $model->data_get(['budget_id' => $budget_id, 'user_id' => $user_id, 'del_time' => 0]);
        if (!$data) {
            return self::error_return('预算不存在');
        }
        $model->data_update(['budget_id' => $budget_id], ['del_time' => time()]);
        return self::success_return('删除成功');
    }
}
